package com.coolweather.android.view.fragment

import android.app.ProgressDialog
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.ListView
import android.widget.TextView
import androidx.drawerlayout.widget.DrawerLayout
import androidx.fragment.app.Fragment
import com.coolweather.android.MainActivity
import com.coolweather.android.R
import com.coolweather.android.WeatherActivity
import com.coolweather.android.db.City
import com.coolweather.android.db.County
import com.coolweather.android.db.Province
import com.coolweather.android.util.HttpUtil
import com.coolweather.android.util.ToastUtil
import com.coolweather.android.util.Utility
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import org.litepal.LitePal
import java.io.IOException

/**
 * 选择地区 Fragment
 * @author by liliang on 2020/6/4 1:43 PM
 */
class ChooseAreaFragment : Fragment() {

    companion object {
        // 省
        const val LEVEL_PROVINCE = 0

        // 市
        const val LEVEL_CITY = 1

        // 县
        const val LEVEL_COUNTY = 2

        const val TYPE_PROVINCE = "province"
        const val TYPE_CITY = "city"
        const val TYPE_COUNTY = "county"
    }


    private lateinit var titleText: TextView
    private lateinit var backBtn: Button
    private lateinit var listView: ListView
    private lateinit var adapter: ArrayAdapter<String>

    /**
     *  加载数据进度  ProgressDialog 已过时, 替换方案: ProgressBar
     */
    private var progressDialog: ProgressDialog? = null

    private var dataList = arrayListOf<String>()

    // 省列表
    private lateinit var provinceList: MutableList<Province>

    // 市列表
    private lateinit var cityList: MutableList<City>

    // 县(区)列表
    private lateinit var countyList: MutableList<County>

    // 选中的省份
    private lateinit var selectedProvince: Province

    // 选中的城市
    private lateinit var selectedCity: City

    // 当前选中的级别
    private var currentLevel = LEVEL_PROVINCE

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.choose_area, container, false)
        titleText = view.findViewById(R.id.title_text)
        backBtn = view.findViewById(R.id.back_button)
        listView = view.findViewById(R.id.list_view)
        adapter = ArrayAdapter(requireContext(), android.R.layout.simple_list_item_1, dataList)
        listView.adapter = adapter
        return view
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        listView.setOnItemClickListener { _, _, position, _ ->
            when (currentLevel) {
                LEVEL_PROVINCE -> {
                    selectedProvince = provinceList[position]
                    // 查询城市
                    queryCities()
                }
                LEVEL_CITY -> {
                    selectedCity = cityList[position]
                    // 查询县
                    queryCounties()
                }
                LEVEL_COUNTY -> {
                    val weatherId = countyList[position].weatherId
                    if (activity is MainActivity) {
                        val intent = Intent(activity, WeatherActivity::class.java).apply {
                            putExtra("weather_id", weatherId)
                        }
                        startActivity(intent)
                        requireActivity().finish()
                    } else if (activity is WeatherActivity) {
                        (activity as WeatherActivity).apply {
                            drawerLayout.closeDrawers()
                            swipeRefresh.isRefreshing = true
                            requestWeather(weatherId)
                            this.weatherId = weatherId
                        }
                    }

                }
            }
        }
        backBtn.setOnClickListener {
            when (currentLevel) {
                LEVEL_COUNTY -> {
                    // 查询城市
                    queryCities()
                }
                LEVEL_CITY -> {
                    // 查询省份
                    queryProvinces()
                }
            }
        }
        // 查询省份
        queryProvinces()
    }

    /**
     * 查询全国所有省份(优先从本地查询,查询不到再去服务器查询
     */
    private fun queryProvinces() {
        titleText.text = "中国"
        backBtn.visibility = View.GONE
        provinceList = LitePal.findAll(Province::class.java)
        if (provinceList.size > 0) {
            dataList.clear()
            for (province in provinceList) {
                dataList.add(province.provinceName)
            }
            adapter.notifyDataSetChanged()
            listView.setSelection(0)
            currentLevel = LEVEL_PROVINCE
        } else {
            val address = "http://guolin.tech/api/china"
            queryFromServer(address, TYPE_PROVINCE)
        }
    }

    /**
     * 查询选中省的所有市(优先从本地查询,查询不到再去服务器查询
     */
    private fun queryCities() {
        titleText.text = selectedProvince.provinceName
        backBtn.visibility = View.VISIBLE
        cityList = LitePal.where("provinceId = ?",
                                        (selectedProvince.id).toString()).find(City::class.java)
        if (cityList.size > 0) {
            dataList.clear()
            for (city in cityList) {
                dataList.add(city.cityName)
            }
            adapter.notifyDataSetChanged()
            listView.setSelection(0)
            currentLevel = LEVEL_CITY
        } else {
            val provinceCode = selectedProvince.provinceCode
            val address = "http://guolin.tech/api/china/$provinceCode"
            queryFromServer(address, TYPE_CITY)
        }
    }

    /**
     * 查询选中市的所有县(优先从本地查询,查询不到再去服务器查询
     */
    private fun queryCounties() {
        titleText.text = selectedCity.cityName
        backBtn.visibility = View.VISIBLE
        countyList =
            LitePal.where("cityId = ?", (selectedCity.id).toString()).find(County::class.java)
        if (countyList.size > 0) {
            dataList.clear()
            for (county in countyList) {
                dataList.add(county.countyName)
            }
            adapter.notifyDataSetChanged()
            listView.setSelection(0)
            currentLevel = LEVEL_COUNTY
        } else {
            val provinceCode = selectedProvince.provinceCode
            val cityCode = selectedCity.cityCode
            val address = "http://guolin.tech/api/china/$provinceCode/$cityCode"
            queryFromServer(address, TYPE_COUNTY)
        }
    }

    /**
     * 服务器查询数据
     * @param address api 地址
     * @param type 查询的数据类型
     */
    private fun queryFromServer(address: String, type: String) {
        // 显示加载进度条
        showProgressDialog()
        HttpUtil.sendOkHttpRequest(address, object : Callback {

            override fun onResponse(call: Call, response: Response) {
                val responseText = response.body?.string()
                var result = false
                when (type) {
                    TYPE_PROVINCE -> result = Utility.handleProvinceResponse(responseText)
                    TYPE_CITY -> result =
                        Utility.handleCityResponse(responseText, selectedProvince.id)
                    TYPE_COUNTY -> result =
                        Utility.handleCountyResponse(responseText, selectedCity.id)
                }
                if (result) {
                    // getActivity 有可能是空的
                    activity!!.runOnUiThread {
                        // 关闭进度条
                        closeProgressDialog()
                        when (type) {
                            TYPE_PROVINCE -> queryProvinces()
                            TYPE_CITY -> queryCities()
                            TYPE_COUNTY -> queryCounties()
                        }
                    }
                }
            }

            override fun onFailure(call: Call, e: IOException) {
                // 通过 runOnUiThread() 方法回到主线程处理逻辑
                activity!!.runOnUiThread {
                    // 关闭进度条
                    closeProgressDialog()
                    ToastUtil.showShort(context, "加载失败")
                }
            }
        })
    }

    /**
     * 显示进度对话框
     */
    private fun showProgressDialog() {
        if (progressDialog == null) {
            progressDialog = ProgressDialog(activity).apply {
                setMessage("正在加载...")
                setCanceledOnTouchOutside(false)
            }
        }
        progressDialog?.show()
    }

    /**
     * 关闭进度对话框
     */
    private fun closeProgressDialog() {
        if (progressDialog != null) {
            progressDialog?.dismiss()
        }
    }
}
